<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .divDrag {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: red;
    }

    .divTarget {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      width: 400px;
      height: 400px;
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <div class="divDrag" draggable="true"></div>
  <div class="divTarget"></div>
  <script>
    // 所有的元素，当拖拽周期结束时，默认事件都是回到原处
    // 一个行为可以不止触发一个事件
    const divDrag = document.querySelector('.divDrag');
    let beginX = 0;
    let beginY = 0;
    divDrag.ondragstart = (e) => {
      e.dataTransfer.effectAllowed = 'link'; // 设置拖拽的效果 link | move | copy | none | all | uninitialized
      beginX = e.clientX; //  拖拽开始时，鼠标相对于浏览器窗口的位置
      beginY = e.clientY; //  拖拽开始时，鼠标相对于浏览器窗口的位置
    };
    divDrag.ondragend = (e) => {
      const x = e.clientX - beginX;
      const y = e.clientY - beginY;
      divDrag.style.left = divDrag.offsetLeft + x + "px";  // 拖拽结束时，div的左上角相对于浏览器窗口的位置
      divDrag.style.top = divDrag.offsetTop + y + "px";  // 拖拽结束时，div的左上角相对于浏览器窗口的位置
    };
    const divTarget = document.querySelector('.divTarget');
    // 拖拽的鼠标进入目标元素区域
    divTarget.ondragenter = (e) => {

    };
    // 拖拽到目标元素上方
    divTarget.ondragover = (e) => {
      e.preventDefault(); // 阻止默认事件
    };
    // 拖拽离开目标元素区域
    divTarget.ondragleave = (e) => {

    };
    // 拖拽放下
    divTarget.ondrop = (e) => {
      e.dataTransfer.dropEffect = 'link'; // 设置放下的效果 link | move | copy | none | all | uninitialized
    };
  </script>
</body>

</html>